﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using Microsoft.Win32;

namespace MoveFiles
{
    public partial class Form1 : Form
    {
        private string _SrcPath;
        private string _DstPath;
        private RegistryHelper _reghelper = new RegistryHelper();
        public Form1()
        {
            InitializeComponent();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            LoadConfig();
            if (File.Exists("Setconfig.ini"))
            {
                textBoxDstPath.Text = _DstPath;
                textBoxSrcPath.Text = _SrcPath;
            }
            else
            {
                MoveFile();
                this.Close();
            }
        }
        private void LoadConfig()
        {
            _reghelper.ReadSettings();
            _SrcPath = _reghelper.Src;
            _DstPath = _reghelper.Dst;
        }
        private void buttonSetConfig_Click(object sender, EventArgs e)
        {
            _reghelper.Dst = _DstPath = textBoxDstPath.Text;
            _reghelper.Src = _SrcPath = textBoxSrcPath.Text;
            _reghelper.SaveSettings();
            MessageBox.Show("已保存");
        }
        private void buttonMoveFiles_Click(object sender, EventArgs e)
        {
            MoveFile();
        }
        private void MoveFile()
        {
            if (_DstPath == "" || _SrcPath == "" || !Directory.Exists(_SrcPath) || !Directory.Exists(_DstPath))
                return;
            if (!_DstPath.EndsWith("\\"))
                _DstPath += "\\";
            string NewImgsPath = _DstPath + DateTime.Now.ToString("yyyyMMdd-hhmmss");
            DirectoryInfo disrc = new DirectoryInfo(_SrcPath);
            DirectoryInfo didst = new DirectoryInfo(_DstPath);
            if (disrc.GetFiles().Length > 0 || disrc.GetDirectories().Length>0)
            {
                if (disrc.Root == didst.Root)
                    Directory.Move(_SrcPath, NewImgsPath);
                else
                {
                    IOFileOper.MoveFolder(_SrcPath, NewImgsPath);
                }
            }
        }
    }
    public class RegistryHelper
    {
        public static void SaveSetting(string Key, string Value)
        {
            RegSetting.WriteSetting(SoftName, Key, Value);
        }
        public static void SaveSetting(string Key, int Value)
        {
            SaveSetting(Key, Value.ToString());
        }
        public static string ReadSetting(string Key, string Default = "")
        {
            return RegSetting.ReadSetting(SoftName, Key, Default);
        }
        public Boolean ReadSettings()
        {
            try
            {               
                Src = ReadSetting("SrcPath");
                Dst = ReadSetting("DstPath");
            }
            catch
            {
                Clear();
                return false;
            }
            return true;
        }
        private void Clear()
        {
            Src = "";
            Dst = "";
        }
        public void SaveSettings()
        {
            SaveSetting("SrcPath", Src);
            SaveSetting("DstPath", Dst);          
        }
       
        private static string SoftName = "MoveFileV1.0";
        public string Src { get; set; }
        public string Dst { get; set; }
    }
    public class RegSetting
    {
        public static void WriteSetting(string Section, string Key, string Setting) // name = key value=setting Section= path
        {
            if (!Section.StartsWith(RootSection))
            {
                if (Section.StartsWith("\\"))
                    Section = Section.Substring(1);
                Section = RootSection + Section;
            }
            RegistryKey key1 = Registry.LocalMachine.CreateSubKey(Section); // .LocalMachine.CreateSubKey("Software\\mytest");
            if (key1 == null)
            {
                return;
            }
            try
            {
                key1.SetValue(Key, Setting);
            }
            catch (Exception exception1)
            {
                return;
            }
            finally
            {
                key1.Close();
            }
        }
        // 读取注册表       
        public static string ReadSetting(string Section, string Key, string Default = "")
        {
            if (!Section.StartsWith(RootSection))
            {
                if (Section.StartsWith("\\"))
                    Section = Section.Substring(1);
                Section = RootSection + Section;
            }
            RegistryKey registryKey = Registry.LocalMachine.OpenSubKey(Section);
            if (registryKey != null)
            {
                object objValue = registryKey.GetValue(Key, Default);
                if (objValue != null)
                {
                    Default = objValue.ToString();
                }
                registryKey.Close();
            }
            return Default;
        }
        private static string RootSection = "SOFTWARE\\JHSOFT\\";
    }
    public class IOFileOper
    {
        /// <summary>
        /// 递归Copy
        /// </summary>
        /// <param name="sourceFolder"></param>
        /// <param name="targetFolder"></param>
        /// <returns></returns>
        public static bool CopyFolder(string sourceFolder, string targetFolder)
        {
            try
            {
                if (targetFolder[targetFolder.Length - 1] != Path.DirectorySeparatorChar)
                {
                    targetFolder += Path.DirectorySeparatorChar;
                }
                if (!Directory.Exists(targetFolder))
                {
                    Directory.CreateDirectory(targetFolder);
                }
                // 得到源目录的文件列表，里面是包含文件以及目录路径的一个数组
                string[] fileList = Directory.GetFileSystemEntries(sourceFolder);
                foreach (var file in fileList)
                {
                    // 先当作目录处理如果存在这个目录就递归Copy该目录下面的文件
                    if (Directory.Exists(file))
                    {
                        CopyFolder(file, targetFolder + Path.GetFileName(file));
                    }
                    else// 否则直接Copy文件
                    {
                        File.Copy(file, targetFolder + Path.GetFileName(file), true);
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                return false;
                throw new Exception(ex.Message, ex);
            }
        }

        /// <summary>
        /// 递归Delete
        /// </summary>
        /// <param name="floderPath"></param>
        /// <returns></returns>
        public static bool DeleteFolder(string floderPath)
        {
            try
            {
                if (Directory.Exists(floderPath))
                {
                    var r = Directory.GetFileSystemEntries(floderPath);
                    foreach (var inst in Directory.GetFileSystemEntries(floderPath))
                    {
                        if (File.Exists(inst))
                        {
                            File.Delete(inst); //直接删除其中的文件 
                        }
                        else
                        {
                            DeleteFolder(inst); //递归删除子文件夹 
                        }
                    }
                    //删除已空文件夹 
                    Directory.Delete(floderPath);
                }
                return true;
            }
            catch (Exception ex)
            {
                return false;
                throw new Exception(ex.Message, ex);
            }
        }
        /// <summary>
        /// Directory.Delete
        /// </summary>
        /// <param name="floderPath"></param>
        /// <returns></returns>
        public static bool DeleteFolder1(string floderPath)
        {
            try
            {
                Directory.Delete(floderPath, true);
                return true;
            }
            catch (Exception ex)
            {
                return false;
                throw new Exception(ex.Message, ex);
            }
        }

        public static bool MoveFolder(string sourceFolder, string targetFolder)
        {
            // 检查目标目录是否以目录分割字符结束,如果不是则添加
            if (targetFolder[targetFolder.Length - 1] != Path.DirectorySeparatorChar)
            {
                targetFolder += Path.DirectorySeparatorChar;
            }
            if (sourceFolder[sourceFolder.Length - 1] != Path.DirectorySeparatorChar)
            {
                sourceFolder += Path.DirectorySeparatorChar;
            }

            List<string> fileNames = new List<string>();

            if (Directory.Exists(sourceFolder))
            {
                //得到所有文件路径
                fileNames.AddRange(Directory.GetFiles(sourceFolder, "*", SearchOption.AllDirectories));
                if (fileNames.Count > 0)
                {
                    //同盘符
                    if (sourceFolder[0].Equals(targetFolder[0]))
                    {
                        if (Directory.Exists(targetFolder))
                        {
                            Directory.Delete(targetFolder, true);
                        }
                        Directory.Move(sourceFolder, targetFolder);
                        return true;
                    }
                    else
                    {
                        if (!Directory.Exists(targetFolder))
                        {
                            Directory.CreateDirectory(targetFolder);
                        }
                        DirectoryInfo dir = new DirectoryInfo(sourceFolder);
                        DirectoryInfo[] folders = dir.GetDirectories("*", SearchOption.AllDirectories);

                        for (int i = 0; i < folders.Length; i++)
                        {
                            string name = folders[i].FullName.Replace(sourceFolder, targetFolder);
                            if (!Directory.Exists(name))
                            {
                                Directory.CreateDirectory(name);
                            }
                        }

                        foreach (string filename in fileNames)
                        {
                            string fn = filename.Replace(sourceFolder, targetFolder);
                            if (File.Exists(fn))
                            {
                                File.Delete(fn);
                            }
                            File.Move(filename, filename.Replace(sourceFolder, targetFolder));
                        }
                        //删除空的目录结构
                        Directory.Delete(sourceFolder, true);
                        return true;
                    }
                }
            }
            return false;
        }
    }

}
